<template>
  <div style="position: relative;">

    <div class="div-box">
      <div v-if="isdisabled" @click.stop="openXy()" class="noclick-tip"></div>
      <gz-checker v-else v-model="selected" @handleChange="handleChange"></gz-checker>
      <div class="file-box">
        使用此服务需您本人同意并签署
        <span class="file" v-for="(item,index) in fileinfoList" :key="index" @click="openXy()">
          <span :style="item.read?'color:#c26ae0':''">《{{ item.name }}》{{ index == (fileinfoList.length - 1) ? '。' : '、' }}</span>
        </span>
      </div>
    </div>

    <div id="modalId" class="modal-box" v-if="modal">
      <div class="title">
        <div style="width: 2rem" @click="modal=false">
          <van-icon name="cross" size="2rem"/>
        </div>
        <p>阅读并签署以下协议</p>
        <div style="width: 2rem"></div>
      </div>
      <div class="content" ref="pdfContent" @scroll.passive="getScroll($event)">
        <!--变量区域-->
        <div class="bl_box">
          <div class="box_title" v-if="valueShow == true">贷款申请书</div>
          <div class="box_text" v-if="valueShow == true">
            XX农商银行：
          </div>
          <div class="box_text" v-if="valueShow == true">
            本人向贵行申请贷款人民币
            <span v-if="!RMBTestAmt">________</span>
            <div v-else class="else_border">
              {{ RMBTestAmt }}
            </div>

            （￥
            <span v-if="!RMBAmt">________</span>
            <div v-else class="else_border">
              {{ RMBAmt }}元
            </div>
            ）。
          </div>
          <div class="box_text" v-if="valueShow == true">
            本人姓名：<span v-if="!name">___________</span>
            <div v-else class="else_border">
              {{ name }}
            </div>
          </div>
          <div class="box_text" v-if="valueShow == true">
            身份证号：<span v-if="!numbercard">____________________</span>
            <div v-else class="else_border">
              {{ numbercard }}
            </div>
          </div>
          <div class="box_text" v-if="valueShow == true">
            资金用途：<span v-if="!loanPurpose">___________</span>
            <div v-else class="else_border">
              <!--              {{ loanPurpose }}-->
              <ab-dict :show-span="true" v-model="loanPurpose" readonly-show-text="true" dict-key="dkyt"></ab-dict>
            </div>
          </div>
          <div class="box_text" v-if="valueShow == true">
            资金用途类型：<span v-if="!loanPurposeType">___________</span>
            <div v-else class="else_border">
              {{ loanPurposeType }}
            </div>
          </div>
          <div class="box_text" v-if="valueShow == true">
            本人自愿申请并郑重声明以上贷款用途真实，且保证贷款资金不用于投入股市、权益性投资及其它任何国家政策、法律、法规所禁止的用途。
          </div>
          <div class="box_text" v-if="valueShow == true">
            特此声明。
          </div>
        </div>
        <div class="">
          <!-- <img src="../../assets/0001.jpg" alt="" style="width:100%">
          <img src="../../assets/0002.jpg" alt="" style="width:100%">
          <img src="../../assets/0003.jpg" alt="" style="width:100%"> -->
        </div>
        <div class="box_text" style="text-align: right;position: relative;margin-right: 2rem">
          客户签名：<span>____________________</span>
          <!-- 签名后的图片 -->
          <img v-if="sign_url" :src="'data:image/png;base64,'+ sign_url" alt="" style="width:12rem;height: auto;
                position: absolute;bottom: 0.2rem;right: 0;">
        </div>
        <!--        </div>-->
      </div>
      <div class="footer" v-if="!selected">
        <x-button type="warn" action-type="button" @click.native="finish" :disabled="!finished">
          <span v-if="!finished">{{ count ? count + 's' : "" }}请滑动至底部完成阅读</span>
          <span v-else>我同意并签署</span>
        </x-button>
      </div>
    </div>
    <!--    签字弹框-->
    <div>
      <!-- 挂载到 body 节点下 -->
      <van-popup v-model="showSignName" :style="{ height: '100%',width:'100%' }" get-container="#modalId">
        <div style="height: 100%;width: 100%;">
          <div class="header_box">
            <x-header class="header" :left-options="{ backText: '', preventGoBack: true }" @on-click-back="closeSignName">采集签名</x-header>
          </div>
          <div class="content_box">
            <canvas-signname @preview-image="getPreview" :show-sign-name="showSignName"></canvas-signname>
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
export default {
  name: 'abLoan',
  props: ['formkey', 'value', 'result', 'tab', 'dataObject', 'fileList'],
  data() {
    return {
      sign_url: '',
      timerRunning: false,
      model: false,
      isCrop: false,
      lineWidth: 6,
      bgColor: '',
      lineColor: 'red',
      resimg: '',//签名图片
      RMBAmt: '', //小写
      RMBTestAmt: '',//大写
      name: '',
      numbercard: '',
      loanPurpose: '',//用途
      keyWord: '',//声明人
      loanPurposeType: '',//资金用途类型
      businessNum: '',//合同号
      valueShow: true,
      descriptionid: '',//影像树上传id
      pdfId: '',
      imgId: '',
      selected: '',//是否签署
      fileinfoList: [],
      modal: false,//借款合同弹框
      count: null,//倒计时
      finished: false,//阅读完成
      showSignName: false,//签字弹框
      scrollBottom: 100,//滚动条
      isdisabled: this.value == 1 ? false : true,  //未阅读不可点
    }
  },
  created() {
    let fileinfoLis = [
      {
        name: this.fileList || '个人借款合同',
        key: 'information',
        content: ''
      }
    ]
    this.fileinfoList = fileinfoLis
    //获取缓存中保存的节点名称，如果是"NHED_SQQS"，证明是借款人的签名，否则是配偶的
    // var formvalue = sessionStorage.getItem('formvalue')
    // if (formvalue == 'NHED_SQQS' || formvalue == 'NHXFD_SQQS') {
    //   this.valueShow = true
    // } else {
    //   this.valueShow = false
    // }
    this.name = this.dataObject['WF_DRAW_BASE']['CUST_LGL_NAM']
    this.numbercard = this.dataObject['WF_DRAW_BASE']['NUM_OF_IDV_ID_DOC']
    this.loanPurpose = this.dataObject['WF_CONTRAC_DRAW_INFO']['LOAN_USE']
    this.loanPurposeType = '010'
    if (this.loanPurposeType == "010") {
      this.loanPurposeType = '消费类'
    }
    if (this.loanPurposeType == "020") {
      this.loanPurposeType = '经营类'
    }
    if (this.loanPurposeType == "030") {
      this.loanPurposeType = '房贷类'
    }
    this.RMBAmt = this.dataObject['WF_CONTRAC_DRAW_INFO']['LOAN_AMT']
    this.businessNum = '11111'
    this.keyWord = '22222'
    if (this.RMBAmt) {
      this.translateAmount()
    }
  },
  mounted() {
    // this.getImageInfo()
  },
  methods: {
    openXy() {
      let that = this
      that.modal = true
      //  倒计时
      that.count = 5
      let timer = setInterval(() => {
        that.count--
        if (that.count <= 0) {
          that.count = null
          clearInterval(timer)
          if (that.scrollBottom < 10) {
            this.finished = true
          }
        }
      }, 1000)
    },
    //复选框改变
    handleChange(val) {
      console.log("000000000000000000000000000000", val)
    },
    /**
     * 获取得到的签名
     * @param val
     */
    getPreview(val) {
      var base64Url = val.replace(/data.+?;base64,/, '')//调用接口
      this.sign_url = base64Url
      this.closeSignName()
      this.isdisabled = false
      this.selected = true;
      this.$emit('input', true)
    },
    //关闭签字按钮
    closeSignName() {
      this.modal = false
      this.showSignName = false
    },
    getScroll(event) {
      // 滚动条距离底部的距离scrollBottom
      this.scrollBottom = event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight;
      // //console.log("当前距离底部距离：------", this.scrollBottom)
      if (!this.finished && this.scrollBottom < 10 && this.count <= 0) {
        this.finished = true
      }
    },
    //阅读完成后弹出
    finish() {
      //  弹出签字页面
      this.showSignName = true
    },
    // 获取图片反显信息
    getImageInfo() {
      let params = {
        fileNumber: this.value.INST_ID,
        fileType: '96030104',
      };
      if (this.valueShow == true) {
        params.fileType = '96030104'
      } else {
        params.fileType = '96030202'
      }
      //console.log("图片返现----------：", params)
      this.abHttpUtil
        .getParams(`/image/queryFiles`, params)
        .then((res) => {
          if (res.isOk) {
            var imglist = res.data
            if (imglist.length > 0) {
              for (var i = 0; i < imglist.length; i++) {
                if (imglist[i].subSet == '002') {
                  this.sign_url = imglist[i].base64
                  this.descriptionid = imglist[i].description
                  this.imgId = imglist[i].description
                } else {
                  this.pdfId = imglist[i].description
                }
              }
            } else {
              this.descriptionid = ''
              this.sign_url = ''
            }
          }
        })
        .catch((error) => {
        });
    },
    // 小写数字转换大写数字
    translateAmount() {
      //定义每个数字对应的大写文字
      const chineseNums = ['', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      //定义十百千万亿
      const levels = ['', '拾', '佰', '仟']
      const unites = ['', '万', '亿', '万亿']
      let num = String(this.RMBAmt)
      let result = ''
      let levesIndex = Math.floor((num.length - 1) / 4)
      for (let i = 0; i < num.length; i++) {
        let dightValue = parseInt(num[i], 10)
        if (dightValue === 0) {
          if ((num.length - i) % 4 === 1) {
            result += unites[levesIndex]
            levesIndex--;
          }
          continue
        }
        result += chineseNums[dightValue] + levels[(num.length - 1 - i) % 4]
        if ((num.length - 1 - i) % 4 === 0 && i !== num.length - 1) {
          result += unites[levesIndex]
          levesIndex--;
        }
      }
      result += '元整'
      this.RMBTestAmt = result
      //
    },
    upload(img) {
      var imageurl = img
      let loading = this.$Message.loading({
        content: "正在上传签名，请稍等...",
        duration: 0
      });

      var data = {
        type: '',//类型，借贷主体1   配偶2
        loanPurposeType: this.loanPurposeType,//贷款用途类型
        businessNum: this.businessNum,//合同号
        fileName: "签字授权书",//文件名称
        keyWord: "客户签名", //签字图片 - 关键字
        userName: this.name,  //姓名
        idNo: this.numbercard, //身份证
        imgFileName: "客户签字",  //签名图片名称
        RMBTestAmt: this.RMBTestAmt, //大写的借钱金额
        RMBAmt: this.RMBAmt,          //小写的
        loanPurpose: this.loanPurpose,       //用途
        operatorCode: "903020100",  //操作员编码或者机构号
        signImg: imageurl,
        resourceId: {
          pdfId: this.pdfId,
          imgId: this.imgId
        },
        subSet: '96030104',
        id: this.descriptionid,		//影像id
        keyWordMap: {
          '本人姓名': this.name,  //姓名
          '身份证号': this.numbercard, //身份证
          '人民币': this.RMBTestAmt, //大写的借钱金额
          '￥': this.RMBAmt,          //小写的
          '资金用途': this.loanPurpose,          //小写的
          '资金用途类型': this.loanPurposeType          //小写的
        }
      }
      if (this.valueShow == true) {
        data.type = '1'
      } else {
        data.type = '2'
        data.keyWordMap = {}
        data.operatorCode = "903020100",  //操作员编码或者机构号
          data.subSet = '96030202'


      }
      var that = this
      that.abHttpUtil.post("/signatures/changePdfText", data).then((res) => {
        loading();
        if (res.comSealAutoPdfCode == '0000') {
          that.$Message.success(res.comSealAutoPdfMessage);
          that.sign_url = imageurl
          this.resimg = ''
        } else {
          this.$Message.error(res.comSealAutoPdfMessage);
        }

      }).catch(error => {
        loading();
        this.$Message.error(error);

      })
    },
    // signbtn() { //弹窗打开签名页面
    //   this.model = true
    // },
    // sginok() { //确定签名
    //   this.$refs.esign.generate().then(res => {//生成图片调用接口，生成签字授权书图片上传影像
    //     this.resimg = res   //签名图片 去掉前缀
    //     var base64Url = this.resimg.replace(/data.+?;base64,/, '')//调用接口
    //     // this.upload(base64Url)
    //   }).catch(err => {
    //   })
    // },
    // sgincancel() { //取消签名
    //   this.resimg = ''
    //   this.$refs.esign.reset()
    // },
    // Reset() {  //清空画板
    //   this.$refs.esign.reset()
    // }
  },
  watch: {
    selected(val) {
      if (!val) {  //有种情况返回false也代表选中   所以返回空
        this.$emit('input', '')
      } else {
        this.$emit('input', val)
      }
    },
    modal(val) {          //解决滑动透传问题
      let body = document.getElementsByTagName('body')[0]
      if (val) {
        body.style.overflow = 'hidden'
      } else {
        body.style.removeProperty("overflow")
      }
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  margin: 0 auto;
  width: 100%;
  //width: 90%;
  //max-height: 5rem;
  //overflow-y: scroll;
  //scrollbar-width: thin;
  //scrollbar-color: transparent transparent;
  //margin: 0.2rem auto;
  //border: 1px solid #333;
  //padding: 0.2rem;
}

.box_title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #000;
  text-align: center;
}

.box_text {
  //width: 100%;
  font-size: 1.4rem;
  font-weight: 600;
  color: #000;
  //line-height: 5rem;
  margin-top: 1.4rem

}

//.content {
//  font-size: 0.15rem;
//  color: #000;
//  line-height: 0.3rem;
//
//  .bl_box {
//    width: 100%;
//
//  }
//}
.bl_box {
  width: 80%;
  margin: 0 auto;
}

.box_footer {
  line-height: 0.2rem;
  font-size: 0.15rem;
  font-weight: 700;
  position: absolute;
  right: 0.5rem;
}

.box_botton {
  width: 2rem;
  height: 0.3rem;
  line-height: 0.3rem;
  text-align: center;
  border-radius: 0.05rem;
  border: 1px solid #ff4a32;
  color: #ff4a32;

}

.else_border {
  border-bottom: 1px solid #000;
  display: inline-block;
  min-width: 2rem;
  text-align: center;
  text-indent: initial;
}

.div-box {
  text-align: left;
  padding: 1rem 2rem;
  position: relative;
  font-size: 1.2rem;
  line-height: 2rem;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;

  .gz-checkbox-box {
    display: unset;
    height: 1.6rem;
    margin-right: 1.2rem;
  }

  .noclick-tip {
    width: 1.5rem;
    height: 1.5rem;
    //position: absolute;
    //left: 2rem;
    //top: 1.3rem;
    background-color: #f8f8f8;
    border: 0.1rem solid #d6d2d2;
    border-radius: 0.2rem;
    margin-right: 1.2rem;
  }

  .file-box {
    flex: 1;
    //margin-left: 26px;
    font-family: HarmonyOS Sans SC;
    font-size: 11px;
    font-weight: 400;
    line-height: 1.6rem;
    text-align: left;
  }

  .file {
    color: var(--primary-color);
    cursor: pointer;
  }
}

.modal-box-bg {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
}

.modal-box {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  padding: 0 0 1rem;
  z-index: 999;
  //border-top-left-radius: 10px;
  //border-top-right-radius: 10px;

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 4.4rem;
    text-align: center;
    color: rgb(29, 33, 41);
    font-family: HarmonyOS Sans SC;
    font-size: 18px;
    font-weight: 500;
    padding: 0 1.6rem;
  }

  .pinch-zoom-container {
    height: auto !important;
  }

  .content {
    overflow: auto;
    height: calc(~'(100% - 10.8rem)');
    //padding: .2rem 0;
    //margin-bottom: 1rem;
    position: relative;

    .iframe-box {
      position: absolute;
      top: -5rem;
      left: 0;
      bottom: 0;
      right: 0;
    }
  }

  .footer {
    height: 6.4rem;
    padding: 0 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;

    .weui-btn_disabled {
      opacity: 0.5;
    }

    .weui-btn_warn {
      height: 4.4rem;
      color: rgb(255, 255, 255);
      font-family: HarmonyOS Sans SC;
      font-size: 16px;
      font-weight: 500;
      border-radius: 40px;
      background: linear-gradient(270.00deg, var(--primary50-color), var(--primary-color));
    }

    //button.weui-btn {
    //  background-color: #FF4A32;
    //}
  }
}

.content_box {
  //padding: 1.2rem;
  height: calc(~'(100vh - 4.6rem)');
  //position: relative;
  /* margin: 1.2rem; */
  /* border: 1px solid #EEEEEE; */
}
</style>
